home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2293 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: erich.triumf.ca!bennett
  2. From: bennett@erich.triumf.ca (P.Bennett)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: why is this an infinite loop?
  5. Date: 19 Jan 1996 23:07 PST
  6. Organization: TRIUMF: Tri-University Meson Facility
  7. Distribution: world
  8. Message-ID: <19JAN199623075074@erich.triumf.ca>
  9. References: <4dp9p5$jm2@news1.wolfe.net>
  10. NNTP-Posting-Host: erich.triumf.ca
  11. News-Software: VAX/VMS VNEWS 1.50    
  12.  
  13. In article <4dp9p5$jm2@news1.wolfe.net>, neus@wolfenet.com (Bill Campbell) writes...
  14. >Beginning c student can't figure out why this small function  to read in a 
  15. >value for the variable x causes an infinite loop when it receives unexpected 
  16. >input.
  17. >double get_x()
  18. >{
  19. > int test;
  20. > double x;
  21. > printf("Enter a numeric value for x: ");
  22. > while(scanf("%lf", &x) != 1)
  23.  
  24. When scanf() is looking for numbers, it is _extremely_ intolerant of unexpected
  25. input - if it gets a non-numeric char, it puts the char back in the input
  26. buffer and returns.  On the next pass, it finds that same char, still doesn't
  27. like it, so puts it back......
  28.  
  29. A much better way to handle user input is to use fgets() to get the input into
  30. a buffer, then sscanf() or other functions to parse what's in the buffer -
  31. much safer, and easier to ask the user to try again.
  32.  
  33. (NEVER use gets()!)
  34.  
  35.  
  36. Peter Bennett VE7CEI                | Vessels shall be deemed to be in sight
  37. Internet: bennett@triumf.ca         | of one another only when one can be
  38. Packet: ve7cei@ve7kit.#vanc.bc.ca   | observed visually from the other
  39. TRIUMF, Vancouver, B.C., Canada     |                          ColRegs 3(k)
  40. GPS and NMEA info and programs: ftp://sundae.triumf.ca/pub/peter/index.html
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.